export const insertTab = (event) => {
  const { target } = event;
  const { selectionStart, selectionEnd } = target;

  // 如果有选中的文本，则替换为两个空格
  if (selectionStart !== selectionEnd) {
    target.value = `${target.value.substring(0, selectionStart)}  ${target.value.substring(selectionEnd)}`;
    // 更新光标位置到替换后的两个空格之后
    target.setSelectionRange(selectionStart + 2, selectionStart + 2);
  } else {
    // 没有选中的文本，直接在光标处插入两个空格
    target.value = `${target.value.substring(0, selectionStart)}  ${target.value.substring(selectionStart)}`;
    // 更新光标位置到新插入的两个空格之后
    target.setSelectionRange(selectionStart + 2, selectionStart + 2);
  }
};


export const checkPoliciesContent = (value, callback) => {
  try {
    const jsonObject = JSON.parse(value)
    if (Array.isArray(jsonObject.statement)) {
      const statementObjectList = jsonObject.statement
      if (jsonObject.statement.length === 0) {
        throw new Error('无效的策略！')
      }
      statementObjectList.forEach(statement => {
        if (typeof statement !== 'object') {
          throw new Error('statement数组中的元素必须是对象！')
        }
        let isAction = false;
        let isResouce = false;
        for (let key in statement) {
          // 键只能为action或resource, 这两个键必须同时存在, 并且这两个键的值必须为数组类型
          if (key !== 'action' && key !== 'resource') {
            throw new Error('statement数组中的对象的键只能为 action 或 resource！')
          }
          if (key === 'action' && Array.isArray(statement[key])) {
            isAction = true
          }
          if (key === 'resource' && Array.isArray(statement[key])) {
            isResouce = true
          }
        }
        if (!isAction || !isResouce) {
          throw new Error('statement数组中的对象必须有 action 和 resource 这两个键且对应值必须为数组')
        }
      });
    } else {
      throw new Error()
    }
    callback()
  } catch (e) {
    callback(new Error(e.message || 'Json格式错误！'))
  }
}